<template>
  <!-- 月度回报 -->
  <div :id="id" :class="className" :style="{height:height+'px',width:width}" />
</template>

<script>
import * as echarts from 'echarts'
import { getMonthlyIndexDistributed, getIndexNetWorthByQuarter, getIndexNetWorthByYear, getIndexNetWorthBySegment } from '@/api/policyManage'
import resize from './mixins/resize'
import { deepClone } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 400
    },
    yName: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    chart_date: {
      type: Array,
      default: () => {
        return []
      }
    },
    name_contrast: {
      type: String,
      default: ''
    },
    month_contrast: {
      type: Number
    },
    showMonth_navList_active: Number,
    navActive: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      chart: null,
      listLoading: false,
      xDate: [],
      data_obj: {},
      data1: [],
      hig_val: [],
      low_val: [],
      incomTips: []
    }
  },
  watch: {
    data: {
      handler(newValue) {
        const list = deepClone(newValue)
        list.map((item, i) => {
          const incomValue_tag = Number(item.incomValue)<0 ? '负' : '正'
          if(item.maxIncomValue&&Number(item.maxIncomValue)) {
            const maxIncomValue_tag = Number(item.maxIncomValue)<0 ? '负' : '正'
            if(maxIncomValue_tag == incomValue_tag) {
              if(incomValue_tag == '正') item.maxIncomValue = (item.maxIncomValue - item.incomValue).toFixed(2)
              if(incomValue_tag == '负') item.maxIncomValue = (item.incomValue - item.maxIncomValue).toFixed(2)
            }
          }
          if(item.minIncomValue&&Number(item.minIncomValue)) {
            const minIncomValue_tag = Number(item.minIncomValue)<0 ? '负' : '正'
            if(minIncomValue_tag == incomValue_tag) {
              if(incomValue_tag == '正') item.minIncomValue = (item.minIncomValue - item.incomValue).toFixed(2)
              // if(incomValue_tag == '负') item.minIncomValue = (item.incomValue - item.minIncomValue).toFixed(2)
              if(incomValue_tag == '负') item.minIncomValue = (item.minIncomValue - item.incomValue).toFixed(2)
            }
          }

          // tips下属收益做排序
          this.incomTips[i] = {}
          item.classifyTipsList = item.classifyTipsList.filter(item => item.incom!=null)
          item.strategyTipsList = item.strategyTipsList.filter(item => item.incom!=null)
          if(item.classifyTipsList.length) this.incomTips[i].classifyTipsList = item.classifyTipsList.sort(this.compare('incom'))
          if(item.strategyTipsList.length) this.incomTips[i].strategyTipsList = item.strategyTipsList.sort(this.compare('incom'))
        })
        this.xDate = list.map(item => item.date)
        this.data1 = list.map(item => item.incomValue)
        this.hig_val = list.map(item => item.maxIncomValue)
        this.low_val = list.map(item => item.minIncomValue)

        this.$nextTick(() => {
          this.data_obj = {}
          this.data_obj[this.yName] = this.data1
          this.data_obj['hig_val'] = this.hig_val
          this.data_obj['low_val'] = this.low_val

          if(this.month_contrast) {
            if(this.showMonth_navList_active==0) this.getIndexNetWorthBySegment(this.month_contrast)
            if(this.showMonth_navList_active==1) this.getIndexNetWorthByYear(this.month_contrast)
            if(this.showMonth_navList_active==2) this.getIndexNetWorthByQuarter(this.month_contrast) 
            if(this.showMonth_navList_active==3) this.getMonthlyIndexDistributed(this.month_contrast)
          }else {
            this.initChart(this.xDate, this.data_obj)
          }
        })
      },
      // deep: true,  // 深度监听在修正浮盈浮亏时，会导致监听二次触发
      immediate: true
    },
    month_contrast: {
      handler(val) {
        if(val) {
          // this.getMonthlyIndexDistributed(val) // 获取对比数据
          if(this.showMonth_navList_active==0) this.getIndexNetWorthBySegment(this.month_contrast)
          if(this.showMonth_navList_active==1) this.getIndexNetWorthByYear(this.month_contrast)
          if(this.showMonth_navList_active==2) this.getIndexNetWorthByQuarter(this.month_contrast) 
          if(this.showMonth_navList_active==3) this.getMonthlyIndexDistributed(this.month_contrast)
        }else {
          setTimeout(() => {
            this.chart && this.chart.dispose()
            this.data_obj = {}
            this.data_obj[this.yName] = this.data1
            this.data_obj['hig_val'] = this.hig_val
            this.data_obj['low_val'] = this.low_val
            this.initChart(this.xDate, this.data_obj)
          }, 200)
        }
      },
      immediate: true
    },
    showMonth_navList_active(i) {
      // setTimeout(() => { // todo
      //   if(this.month_contrast) {
      //     if(i==0) this.getIndexNetWorthBySegment(this.month_contrast)
      //     if(i==1) this.getIndexNetWorthByYear(this.month_contrast)
      //     if(i==2) this.getIndexNetWorthByQuarter(this.month_contrast)
      //     if(i==3) this.getMonthlyIndexDistributed(this.month_contrast)
      //   }
      // }, 2000)
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(xDate, obj) {
      this.chart = echarts.init(document.getElementById(this.id))

      // todo
      const img = new Image()
      const img1 = new Image()
      img.src = require('../../assets/bb.png')
      img1.src = require('../../assets/cc.png')

      // const color_list = ['#e16756', '#81b7ec'] //todo 颜色 #42B983
      const series = []
      Object.keys(obj).forEach(key => {
        const item = obj[key]
        if(key=='hig_val' || key=='low_val') {
          const data = []
          item.map(im => {
            data.push({
              name: key,
              value: im,
              itemStyle: {
                // borderColor: im>=0 ? '#e16756' : '#42B983'
                borderColor: '#e16756'
              }
            })
          })
          series.push({
            name: this.yName,
            stack: this.yName,
            type: 'bar',
            barWidth: '20%',
            barMaxWidth: '40',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: { width: 1.5 },
            itemStyle: {
              normal: {
                color: function(params) {
                  return {
                    // image: params.value>=0 ? img : img1,
                    image: img,
                    repeat: 'repeat'
                  }
                },
                barBorderRadius: 0
              },
            },
            data
          })
        }else {
          const data = []
          if(key == this.yName) {
            item.map(im => {
              data.push({
                value: im,
                itemStyle: {
                  // borderColor: im>=0 ? '#e16756' : '#42B983'
                  borderColor: '#e16756'
                }
              })
            })
          }else {
            item.map(im => {
              data.push({
                value: im,
                itemStyle: {
                  borderColor: '#81b7ec'
                }
              })
            })
          }
          series.push({
            name: key,
            stack: key,
            type: 'bar',
            barWidth: '20%',
            barMaxWidth: '40',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: { width: 1.5 },
            itemStyle: {
              normal: {
                color: (params) => {
                  if(params.seriesName == this.yName) {
                    // return params.value>=0 ? '#e16756' : '#42B983'
                    return '#e16756'
                  }else {
                    return '#81b7ec'
                  }
                },
                barBorderRadius: 0
              }
            },
            data
          })
        }
      })

      // 兼容无指数情况
      const legendData = [
        {
          name: this.yName,
          itemStyle: {
            color: '#e16756'
          }
        },
      ]
      if(series.length>3) {
        legendData.push({
          name: series[series.length-1].name,
          itemStyle: {
            color: '#81b7ec'
          }
        })
      }

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(150,150,150,0.3)'
            }
          },
          formatter: (params) => {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].value) {
                str += `<div style="display: flex;align-items: center;">
                ${params[i].name=='hig_val'||params[i].name=='low_val'?params[0].marker:params[i].marker} 
                <span style="flex:1;">${params[i].name=='hig_val'?'浮盈':params[i].name=='low_val'?'浮亏':params[i].seriesName}</span> 
                <span style="margin-left: 10px;font-weight: bold;"> ${params[i].name=='hig_val'?this.data[params[i].dataIndex].maxIncomValue:params[i].name=='low_val'?this.data[params[i].dataIndex].minIncomValue:params[i].value}%</span>
                </div>`
              }else if(i==0) { //当此时间段收益为null时的处理
                str += `<div style="display: flex;align-items: center;">
                ${params[i].marker}
                <span style="flex:1;">${params[i].seriesName}</span>
                <span style="margin-left: 10px;font-weight: bold;">--</span>
                </div>`
              }
            }
            if(this.navActive==1&&this.incomTips[params[0].dataIndex].classifyTipsList&&this.incomTips[params[0].dataIndex].classifyTipsList.length) {
              for (let i = 0; i < this.incomTips[params[0].dataIndex].classifyTipsList.length; i += 1) {
                const obj = this.incomTips[params[0].dataIndex].classifyTipsList[i]
                str += `<div style="display: flex;align-items: center;">
                <span style="flex:1;">${obj.name}</span>
                <span style="margin-left: 10px;font-weight: bold;">${obj.incom}%</span>
                </div>`
              }
            }
            if((this.navActive==2||this.id=="groupManageMonthReturnChart")&&this.incomTips[params[0].dataIndex].strategyTipsList&&this.incomTips[params[0].dataIndex].strategyTipsList.length) {
              for (let i = 0; i < this.incomTips[params[0].dataIndex].strategyTipsList.length; i += 1) {
                const obj = this.incomTips[params[0].dataIndex].strategyTipsList[i]
                str += `<div style="display: flex;align-items: center;">
                <span style="flex:1;">${obj.name}</span>
                <span style="margin-left: 10px;font-weight: bold;">${obj.incom}%</span>
                </div>`
              }
            }
            return str
          }
        },
        grid: {
          left: '8%',
          right: '8%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          x: '12%',
          top: '4%',
          textStyle: {
            color: '#90979c'
          },
          data: legendData
          // data: [
          //   {
          //     name: this.yName,
          //     itemStyle: {
          //       color: '#e16756'
          //       // color: {
          //       //   type: 'linear',
          //       //   x: 0,
          //       //   y: 0,
          //       //   x2: 1,
          //       //   y2: 1,
          //       //   colorStops: [
          //       //     {
          //       //       offset: 0, color: '#e16756' // 0% 处的颜色
          //       //     }, 
          //       //     {
          //       //       offset: 0.5, color: '#e16756' // 0% 处的颜色
          //       //     }, 
          //       //     {
          //       //       offset: 0.51, color: '#42B983' // 0% 处的颜色
          //       //     }, 
          //       //     {
          //       //       offset: 1, color: '#42B983' // 100% 处的颜色
          //       //     }
          //       //   ],
          //       //   global: false
          //       // }
          //     }
          //   },
          //   {
          //     name: series[series.length-1].name,
          //     itemStyle: {
          //       color: '#81b7ec'
          //     }
          //   }
          // ]
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto'
          },
          data: xDate
        }],
        yAxis: [{
          type: 'value',
          // min: 'dataMin',
          // max: 'dataMax',
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#90979c'
            }
          },
          axisTick: {
            show: true,
            alignWithLabel: true
          },
          axisLabel: {
            interval: 0,
            formatter: function(value) {
              // return (value).toFixed(2) + '%'
              return value + '%'
            }
          },
          splitArea: {
            show: false
          }
        }],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          brushSelect: false,
          realtime: true, // 实时更新系列的视图
          height: '7%',
          bottom: '2%',
        }],
        // dataZoom: [
        //   {
        //     id: 'dataZoomX',
        //     type: 'inside',
        //     xAxisIndex: [0],
        //     filterMode: 'none',
        //     start: 0,
        //     end: 100
        //   }
        // ],
        series
      })
    },
    getMonthlyIndexDistributed(indexType) {
      getMonthlyIndexDistributed({
        indexType,
        startTime: this.xDate[0],
        endTime: this.xDate[this.xDate.length-1]
      }).then(res => {
        const _data2 = res.body
        this.data_obj = {}
        this.data_obj[this.yName] = this.data1
        this.data_obj['hig_val'] = this.hig_val
        this.data_obj['low_val'] = this.low_val
        this.data_obj[this.name_contrast] = []
        // this.xDate.map((date, i) => {  // 速度优化
        //   if(_data2[i]&&_data2[i].indexTime) {
        //     if(date == _data2[i].indexTime) {
        //       this.data_obj[this.name_contrast].push(_data2[i].indexGrowthRate)
        //     }else {
        //       let o = _data2.find(d2 => d2.indexTime == date)
        //       if(o) {
        //         this.data_obj[this.name_contrast].push(o.indexGrowthRate)
        //       }else {
        //         this.data_obj[this.name_contrast].push(null)
        //       }
        //     }
        //   }else {
        //     let o = _data2.find(d2 => d2.indexTime == date)
        //     if(o) {
        //       this.data_obj[this.name_contrast].push(o.indexGrowthRate)
        //     }else {
        //       this.data_obj[this.name_contrast].push(null)
        //     }
        //   }
        // })

        this.xDate.map((date, i) => {
          const o = _data2.find(d2 => d2.indexTime == date)
          if(o) {
            this.data_obj[this.name_contrast].push(o.indexGrowthRate)
          }else {
            this.data_obj[this.name_contrast].push(null)
          }
        })

        // this.chart.dispose()
        this.initChart(this.xDate, this.data_obj)
      })
    },
    getIndexNetWorthByQuarter(indexType) {
      getIndexNetWorthByQuarter({
        indexType,
        startTime: this.xDate[0],
        endTime: this.xDate[this.xDate.length-1]
      }).then(res => {
        const _data2 = res.body
        this.data_obj = {}
        this.data_obj[this.yName] = this.data1
        this.data_obj['hig_val'] = this.hig_val
        this.data_obj['low_val'] = this.low_val
        this.data_obj[this.name_contrast] = []

        this.xDate.map((date, i) => {
          const o = _data2.find(d2 => d2.date == date)
          if(o) {
            this.data_obj[this.name_contrast].push(o.incomValue)
          }else {
            this.data_obj[this.name_contrast].push(null)
          }
        })
        this.initChart(this.xDate, this.data_obj)
      })
    },
    getIndexNetWorthByYear(indexType) {
      getIndexNetWorthByYear({
        indexType,
        startTime: this.xDate[0],
        endTime: this.xDate[this.xDate.length-1]
      }).then(res => {
        const _data2 = res.body
        this.data_obj = {}
        this.data_obj[this.yName] = this.data1
        this.data_obj['hig_val'] = this.hig_val
        this.data_obj['low_val'] = this.low_val
        this.data_obj[this.name_contrast] = []
        
        this.xDate.map((date, i) => {
          const o = _data2.find(d2 => d2.date == date)
          if(o) {
            this.data_obj[this.name_contrast].push(o.incomValue)
          }else {
            this.data_obj[this.name_contrast].push(null)
          }
        })
        // this.chart.dispose()
        this.initChart(this.xDate, this.data_obj)
      })
    },
    getIndexNetWorthBySegment(indexType) {
      this.data_obj[this.name_contrast] = []
      getIndexNetWorthBySegment({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1]
      }).then(res => {
        const _data2 = res.body
        this.data_obj = {}
        this.data_obj[this.yName] = this.data1
        this.data_obj['hig_val'] = this.hig_val
        this.data_obj['low_val'] = this.low_val
        this.data_obj[this.name_contrast] = []
        
        this.xDate.map((date, i) => {
          const o = _data2.find(d2 => d2.date == date)
          if(o) {
            this.data_obj[this.name_contrast].push(o.incomValue)
          }else {
            this.data_obj[this.name_contrast].push(null)
          }
        })
        this.initChart(this.xDate, this.data_obj)
      })
    },

    // 排序辅助函数
    compare(property) {
      return function(a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value2 - value1
      }
    }
  }
}
</script>
